# GNAFU - "Ground, Navy and Air Fuck-Up" real-time strategy game
# Copyright (C) 2008-2009 k0wax <k0waxk0wax@gmail.com>
#
# This file is part of GNAFU.
#
# GNAFU is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# GNAFU is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNAFU.  If not, see <http://www.gnu.org/licenses/>.

from __future__ import division, absolute_import
from math import *
import pyglet, noise

def make_noise_data(w, h):
    octaves = 1
    freq = 8.0 * octaves
    rx = (4*4)/4
    ry = rx
    ret = []
    for y in range(h):
        for x in range(w):
            v = int(noise.pnoise2(x / freq, y / freq, octaves, repeatx=rx, repeaty=ry) * 127.0 + 128.0)
            ret.append(v)
    return ret

def pasterize(d):
    nl = 8
    l = int(256 / nl)
    sea_amg = 0.5
    land_amg = 1.0 - sea_amg
    for i in xrange(len(d)):
        v = d[i]
        c = l
        #if v <= 127:
        #    c = l - 8
        #else:
        #    c = l + 10
        d[i] = l * (v // c)
    return d

def data_to_rgba(d):
    ret = ''
    for x in d:
        ret += (chr(x) * 3) + chr(0xff)
    return ret

def data_to_img(d, w, h):
    img = pyglet.image.create(w, h)
    img_data = img.get_image_data()
    img.set_data('RGBA', img_data.pitch, data_to_rgba(d))
    return img
        
def create_layered_noise_image(w, h):
    return data_to_img(pasterize(make_noise_data(w, h)), w, h)

def create_layered_data(w, h, scale=None):
    """return 8 levels data based on thresholded noise"""
    d = pasterize(make_noise_data(w, h))
    for i in xrange(len(d)):
        d[i] = d[i] // 32
    return d
    
if __name__ == "__main__":
    img = create_layered_noise_image(w=32, h=32)
    img.save(filename='noise.png')
